package com.shixun.exception.exception;




import com.shixun.exception.errResult.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(DormException.class)
   // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException customException(DormException e) {
        String msg = e.getMsg();
        return new ResultException(msg);
    }

    //    @ExceptionHandler(Exception.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public ResultException exception(Exception e) {
//        return new ResultException("发生未知错误，请回控制台查看");
//    }
    @ExceptionHandler(MethodArgumentNotValidException.class)//捕获系统异常
    @ResponseBody
   // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
    public ResultException doValidException(MethodArgumentNotValidException argumentNotValidException) {
        //解析异常的信息
        BindingResult bindingResult = argumentNotValidException.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> errMsg = new ArrayList<>();
        fieldErrors.stream().peek((item) -> {
            errMsg.add(item.getDefaultMessage());
        }).collect(Collectors.toList());
        String join = StringUtils.join(errMsg, ",");
        return new ResultException(join);
    }



    @ExceptionHandler(HttpMessageNotReadableException.class)//捕获系统异常
    @ResponseBody
  //  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
    public ResultException doHttpMessageNotReadableException(HttpMessageNotReadableException httpMessageNotReadableException) {
        return new ResultException("输入有误");
    }

}
